package com.intellagric.controller.module;


import com.intellagric.common.bean.LayuiDataGridResult;
import com.intellagric.common.bean.ResponseMessage;
import com.intellagric.common.utils.CookieUtils;
import com.intellagric.interfaces.login.LoginService;
import com.intellagric.interfaces.sys_user.UserService;
import com.intellagric.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: zhy
 * @Date: 2018/10/6
 * @Description: 用户登录控制
 */
@Controller
public class LoginController {

    // LoginService loginServiceImpl=new LoginServiceImpl();   这样子里面的mapper就为空

    @Autowired
    private LoginService loginServiceImpl;
    @Autowired
    private UserService userService;



    @Value("${TOKEN_KEY}")
    private String TOKEN_KEY;

    @Value("${SESSION_EXPIRE}")
    private Integer SESSION_EXPIRE;

    @RequestMapping(value="/login", method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage login(String username, String password,
                                 HttpServletRequest request, HttpServletResponse response) {

        ResponseMessage result = loginServiceImpl.login(request,username,password);
        if (result.getCode() == 200) {  //登录成功
            String token = (String) result.getData().get("user");
            //添加到cookie中
            CookieUtils.setCookie(request,response,TOKEN_KEY,token,SESSION_EXPIRE);

        }

        return result;
    }



    @RequestMapping(value="/admin/user/getIp")
    @ResponseBody
    public String getIp(HttpServletRequest request) {

        String ip = loginServiceImpl.getClientIp(request);
        return ip;
    }


    @RequestMapping(value=" /admin/user/signOut")
    public String signOut(HttpServletRequest request,HttpServletResponse response) {
        CookieUtils.deleteCookie(request,response,TOKEN_KEY);

        return "login";
    }


    //注册

    @RequestMapping(value="/registerInfor", method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage register(SysUser sysUser){

        return userService.addUser(sysUser);
    }

    //注册、编辑用户列表时验证用户名
    @RequestMapping(value="/verifyUserName", method= RequestMethod.POST)
    @ResponseBody
    public ResponseMessage verifyUserName(String loginName){

        return userService.verifyUserName(loginName);
    }
}
